package com.hue.netty.day01.one;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.ArrayList;
import java.util.List;

/*
    使用netty来创建服务端
 */
public class Server {
    public static List<SocketChannel> socketChannelList = new ArrayList<>();

    public static void main(String[] args) {
        /*
            创建两个工作组bossGroup和workerGroup,默认拥有的线程(NioEventGroup)数为cpu核数*2
            默认情况下线程组分配线程的方式为轮询
         */
        //bossGroup只负责处理客户端的连接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //workerGroup负责处理客户端的业务请求
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建服务端的启动配置对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)  //设置线程组
                    .channel(NioServerSocketChannel.class)    //设置服务端的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128)   //设置线程队列得到的连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)  //设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() { //设置通道测试对象
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            System.out.println("当前客户端的channel:"+socketChannel);
                            /*
                                这里可以使用一个集合将所有的客户端的socketChannel全部存储起来，当需要向某些客户端推送消息的时候可以
                                在这些socketChannel的taskQueue或者scheduleTaskQueue中添加任务
                             */
                            socketChannelList.add(socketChannel);
                            //给pipeline设置处理器
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    });
            //绑定端口，并且同步，启动服务器
            ChannelFuture channelFuture = bootstrap.bind(7777).sync();

            //给channelFuture添加监听器
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("注册成功");
                    }else {
                        System.out.println("注册失败");
                    }
                }
            });

            //对关闭通道事件进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
